<?php defined('IN_LK') or die('Access Denied');
/**
 * 模板解析类
 * @author <yangzhiguo0903@163.com>
 */
final class template
{
	/**
	 * 编译模板,生成编译后的文件
	 */
	public function template_compile($module, $file)
	{
		$filename = TPL_ROOT . $module . DIRECTORY_SEPARATOR . $file . '.html';
		/*if(!is_file($filename))
		{
			showmsg("Template file \"$filename\" not exists!");
		}*/
		$cachepath = CACHE_PATH . 'cache_template' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR;
		if(!is_dir($cachepath))
		{
			mkdir($cachepath, 0777, true);  //递归创建
		}
		$compilefile = $cachepath . $file . '.php';
		$content = @file_get_contents($filename);
		$content = $this->template_parse($content);
		$strlen  = file_put_contents($compilefile, $content);
		chmod($compilefile, 0777);
		return $strlen;
	}
	
	/**
	 * 模板解析引擎
	 * @param string $c 模板语言
	 * @param string 
	 */
	private function template_parse($c)
	{
		$c = preg_replace("/\{template\s+(.+)\}/", "<?php include template(\\1);?>", $c);  //{template 'index','admin'}
		$c = preg_replace("/\{include\s+(.+)\}/", "<?php include \\1;?>", $c);  //{include 'index.html'}
		$c = preg_replace("/\{php\s+(.+)\}/", "<?php \\1?>", $c);
		$c = preg_replace("/\{if\s+(.+?)\}/i", "<?php if(\\1) {?>", $c);  //if起始{if $a=1}
		$c = preg_replace("/\{else\}/i", "<?php } else {?>", $c);  //else:{else}
		$c = preg_replace("/\{else\s+if(.+?)\}/i", "<?php }else if(\\1){?>", $c);  //elseif:{else if $a=2}
		$c = preg_replace("/\{\/if\}/i", "<?php }?>", $c);  //endif; {/if}
		$c = preg_replace("/\{loop\s+(\S+)\s+as\s+(\S+)\}/i", "<?php if(is_array(\\1)){ foreach(\\1 as \\2) {?>", $c);
		$c = preg_replace("/\{\/loop\}/i", "<?php }}?>", $c);  //{loop $arr as $val}{/loop}
		$c = preg_replace("/\{loop\s+(\S+)\s+as\s+(\S+)\s*=\>\s*(\S+)\}/i", "<?php if(is_array(\\1)){ foreach(\\1 as \\2=>\\3) {?>", $c);  //{loop $arr as $key=>$val}{/loop}
		$c = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \$\\1;?>", $c);  //输出变量{$a}
		$c = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[(.*?)\]+)\}/", "<?php echo \$\\1\\2;?>",$c);  //输出$arr['a']['c']																	
		$c = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $c);//输出常量
		$c = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $c);
		return "<?php defined('IN_LK') or die('Access Denied');?>\n" . $c;
	}
}